import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  // token
  String _token = '';
  // 刷新token
  String _refreshToken = '';

  // 初始化
  init() async {
    final instance = await _getInstance();
    _token = instance.getString(GlobalVariable.TOKEN_KEY) ?? '';
    _refreshToken = instance.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  // 获取仓库
  Future<SharedPreferences> _getInstance() {
    // 获取仓库实例
    return SharedPreferences.getInstance();
  }

  // 存储token
  setToken(String token, {String? refreshToken}) async {
    final instance = await _getInstance();
    instance.setString(GlobalVariable.TOKEN_KEY, token);
    _token = token;
    if (refreshToken != null) {
      instance.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  // 获取token
  getToken() {
    return _token;
  }

  // 获取刷新token
  getRefreshToken() {
    return _refreshToken;
  }

  // 删除token
  removeToken() async {
    final instance = await _getInstance();
    instance.remove(GlobalVariable.TOKEN_KEY);
    _token = '';
    instance.remove(GlobalVariable.REFRESH_TOKEN_KEY);
    _refreshToken = '';
  }
}

final tokenManager = TokenManager();
